# Create your views here.
import os, json, xlrd
from django.views import View
from django.db.models import Q
from personal_center.models import User
from administrative.models import Company
from personal_center.sql_file import manage_flow
from django.shortcuts import render, redirect, HttpResponse
from personal_center.models import ConferenceRoomApplication
from that_person_center.models import PersonalJournal



class home(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except Exception as E:
            return redirect("/")

        # ======================================================== 我的会议 ========================================================
        meet_obj = ConferenceRoomApplication.objects.filter(Q(names=request.user.real_name) | Q(conferee__contains=request.user.job_number)).order_by("-create_time")[:5]
        # ======================================================== 我的邮件 ========================================================
        letter_obj = request.user.inboxinfopeople_set.filter(deleted='a').order_by("-create_time")[:5]
        # ======================================================== 申请图表 ========================================================
        select_data = manage_flow().my_apply(request.user.id, request.user.real_name, request.user.company.name)
        dep_list, dep_number_list = [], []
        for i in select_data:
            dep_list.append(i[1])
            dep_number_list.append(i[2])
        returnDict = {'realname': request.user.real_name, 'position': request.user.position, 'department': request.user.company.name, "letter_obj": letter_obj, "meet_obj": meet_obj,
                      'dep_list': dep_list, 'dep_number_list': dep_number_list}
        return render(request, 'that_person_center/home.html', returnDict)

class MyBasicInformation(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except Exception as E:
            return redirect("/")
        returnDict = {'realname': request.user.real_name, 'position': request.user.position, 'department': request.user.company.name, "job_number": request.user.job_number,
                      "obj": request.user, 'company_list': [{"id": c.id, "name": c.name} for c in Company.objects.filter(~Q(id__in=[87])).order_by("serial_number")]}
        return render(request, 'that_person_center/MyBasicInformation.html', returnDict)

class InformationModification(View):
    def post(self, request):
        user_id = request.POST.get('user_id')
        department = request.POST.get('department')                      # 部门
        mobile = request.POST.get('mobile', '')                          # 手机号码
        position = request.POST.get('position', '')                      # 职称
        post = request.POST.get('post', '')                              # 行政职位
        mailbox = request.POST.get('mailbox', '')                        # 邮箱
        role = request.POST.get('role', '')                              # 人员类别
        native_place = request.POST.get('native_place', '')              # 籍贯
        political_outlook = request.POST.get('political_outlook', '')    # 政治面貌
        jon_degree = request.POST.get('jon_degree', '')                  # 民族

        obj = User.objects.get(id=int(user_id))
        obj.company = Company.objects.get(id=int(department))
        obj.mobile = mobile
        obj.position = position
        obj.post = post
        obj.mailbox = mailbox
        obj.role = role
        obj.native_place = native_place
        obj.political_outlook = political_outlook
        obj.jon_degree = jon_degree
        obj.save()
        return_dict = {'code': 200, 'message': '修改成功！', 'data': []}
        return HttpResponse(json.dumps(return_dict), content_type="application/json")

class LogManagement(View):
    def get(self, request):
        try:
            real_name = request.user.real_name
        except Exception as E:
            return redirect("/")
        returnDict = {'realname': request.user.real_name, 'position': request.user.position, 'department': request.user.company.name}
        return render(request, 'that_person_center/LogManagement.html', returnDict)

    def post(self, request):
        page = request.POST.get("cPage", 1)
        page_size = request.POST.get("pSize", 20)
        objs = PersonalJournal.objects.filter(preparer=request.user.real_name).order_by('-create_time')
        data_list = [{'id': obj.id, 'log_date': obj.log_date, 'company': obj.company, 'proposed_department': obj.proposed_department, 'content_problems': obj.content_problems,
                      'suggestion_solution': obj.suggestion_solution, "solution_situation": obj.solution_situation, "settlement_date": obj.settlement_date, 'state': obj.preparer,
                      'total_money': obj.remark, "preparer": obj.preparer}
                     for obj in objs[(int(page) - 1) * int(page_size):int(page) * int(page_size)]]
        returnDict = {'status': 'success', "totals": objs.count(), "data": data_list}
        return HttpResponse(json.dumps(returnDict), content_type="application/json")


class UploadExcel(View):
    def post(self, request):
        files = request.FILES.get('file')                      # 正文

        type_file = files.name.split('.')[-1]
        if type_file not in ['xlsx', 'xls']:
            return HttpResponse(json.dumps({"code": 400, 'message': "请上传excel文件！"}))
        read_file = xlrd.open_workbook(filename=None, file_contents=files.read())
        file_table = read_file.sheets()[0]
        file_table_rows = file_table.nrows
        peoples_list = []
        # 读表格数据，从第二行开始，一般第一行都是说明
        try:
            for i in range(1, file_table_rows):
                a = file_table.cell(i, 0)
        except:
            pass
        for t in range(1, file_table_rows):
            PersonalJournal.objects.create(
                log_date=file_table.cell(t, 1).value, company=file_table.cell(t, 2).value, proposed_department=file_table.cell(t, 3).value, content_problems=file_table.cell(t, 4).value,
                suggestion_solution=file_table.cell(t, 5).value, solution_situation=file_table.cell(t, 6).value, settlement_date=file_table.cell(t, 7).value, preparer=file_table.cell(t, 8).value, remark=file_table.cell(t, 9).value
            )

        returnData = {'code': 200, 'message': '上传成功！'}
        return HttpResponse(json.dumps(returnData), content_type="application/json")